//定义用户相关的仓库
import {defineStore} from "pinia";
import {reqUserCode, reqUserLogin} from "@/api/hospital/index.ts";
import type {LoginData, UserInfo} from "@/api/hospital/type.ts";
import {UserLoginResponseData} from "@/api/hospital/type.ts";
import {UserState} from "@/store/modules/interface";
import {GET_TOKEN, REMOVE_TOKEN, SET_TOKEN} from "@/util/user.ts";


const useUserStore = defineStore('User', {
    state: (): UserState => {
        return {
            visible: false,//用于控制登陆组件的dialog显示与隐藏
            code: '',//存储用户验证码
            userInfo: JSON.parse(GET_TOKEN() as string) || ({} as UserInfo)
        }
    },
    actions: {
        //获取验证码的方法
        async getCode(phone: string) {
            //向服务器携带手机号码，获取验证码
            //正常开发只需要发送一个请求，后端就会发到用户手机上
            let result: any = await reqUserCode(phone)
            if (result.code == 200) {
                this.code = result.data
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        //用户手机号登录方法
        async userLogin(data: LoginData) {
            //登录请求
            let result: UserLoginResponseData = await reqUserLogin(data)
            if (result.code == 200) {
                this.userInfo = result.data
                //本地持久化存储用户信息
                SET_TOKEN(JSON.stringify(this.userInfo))
                // 返回一个成功的Promise
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        //用户退出登录的方法
        signOut() {
            this.userInfo = {name: '', token: ''}
            REMOVE_TOKEN()
        },
        //查询微信扫码的接口（看本地存储是否存储数据）
        queryState(){
            //开启轮询查本地是否成功存储用户信息
            let timer = setInterval(()=>{
                if(GET_TOKEN()){
                    //说明本地存储已经有数据；扫码成功
                    //关闭对话框
                    this.visible = false
                    this.userInfo = JSON.parse(GET_TOKEN() as string)
                    clearInterval(timer)
                }
            },1000)
        }
    },
})

export default useUserStore